<?php
/**
 * @Author:      dx
 * @DateTime:    2016-3-9 15:32:48
 * @Description: 用于 优惠券
 */
class MktCouponController extends BaseController
{
    /**
     * @Author:      dx
     * @DateTime:    2016-03-9 09:59:41
     * @Description: 创建优惠券
     */
    public function coupon_create()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required|max:25',
                'type' => 'required',
                // 'amount' => 'required',
                // 'limit_amount' => 'required',
                'code_type' => 'required',
                'limit_type' => 'required',
                'code' => 'max:20',
                // 'desc' => 'required|max:200',
                // 'begin_date'=>'required',
                'status' => 'required',
                // 'count'=>'required',
                'date_type' => 'required',
                'exchange_method' => 'required',
                'limit_num' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            if ((Input::get('type') == 1 || Input::get('type') == 4) && Input::get('amount') == "") {//订单减免 和服务减免必须有减免金额
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if ((Input::get('type') == 2 || Input::get('type') == 4) && Input::get('pack_id') == "") {//服务抵用和 服务减免 必须有服务包
                $response = Lang::get("mkt_error.mkt_coupon_product_package_error_31006");
                break;
            }
            if (Input::get('type') == 5 && (Input::get('discount') == "" || Input::get('pack_id') == "")) {//如果是服务折扣 必须有折扣和服务
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }

            if (Input::get('limit_type') == 1 && Input::get('limit_amount') == "") {//金额限制
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if ((Input::get('limit_type') == 2 || Input::get('limit_type') == 3) && Input::get('pack_id_arr') == "") {//服务限制
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if (Input::get('code_type') == 2 && Input::get('code') == "") { // 2代表统一码
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if (Input::get('date_type') == 1 && Input::get('date_num') == "") {
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if (trim(Input::get('date_type')) == 0 && Input::get('begin_date') == "" && Input::get('end_date') == "") {
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if (Input::get('num_type', 0) == 0 && Input::get('count') == "") {//如果是券的数量是限量 并且没有输入数量 返回错误信息
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if (Input::get('code') != "") {
                //判断优惠券重复添加
                $check_coupon = CouponBaseInfo::where('code', Input::get('code'))->where('status', 1)->first();
                if (!is_null($check_coupon)) {
                    $response = Lang::get("mkt_error.mkt_coupon_code_error_310004");
                    break;
                }
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            if(Input::get('count') > 5000){
                $response = Lang::get("mkt_error.coupon_count_exit_error_510004");
                break;
            }
            if(Input::get('exchange_method') == 2 && Input::get('password') == ""){
                $response = Lang::get("mkt_error.coupon_password_not_exit_error_510006");
                break;
            }
            if(Input::get('limit_num') > 999){
                $response = Lang::get("mkt_error.coupon_only_user_used_num_error_510007");
                break;
            }


            $date_num = trim(Input::get('date_num'));
            if ($date_num) {
                $date_num = trim(Input::get('date_num'));
            } else {
                $date_num = 0;
            }
            $begin_date = Input::get('begin_date');
            if ($begin_date) {
                $begin_date = Input::get('begin_date');
            }
            $end_date = Input::get('end_date');
            if ($end_date) {
                $end_date = Input::get('end_date');
                //检测优惠券是否可以创建
                $today = date("Y-m-d");
                if ($today > $end_date) {
                    $response = Lang::get("mkt_error.mkt_coupon_date_error_310003");
                    break;
                }
            }
            $mc = new CouponBaseInfo();
            $mc->name = Input::get('name');
            $mc->type = Input::get('type');
            $mc->amount = Input::get('amount') * 100;
            $mc->limit_amount = Input::get('limit_amount') * 100;
            $mc->limit_num = Input::get('limit_num') ? Input::get('limit_num') : 1;
            $mc->code_type = Input::get('code_type');
            $mc->code = Input::get('code');
            $mc->desc = Input::get('desc');
            $mc->begin_date = $begin_date ? $begin_date : "0000-00-00";
            $mc->end_date = $end_date ? $end_date : "0000-00-00";
            $mc->count = Input::get('count');
            $mc->num_type = Input::get('num_type', 0);
            $mc->date_type = Input::get('date_type');
            $mc->date_num = $date_num;
            $mc->status = Input::get('status');
            $mc->created_by = $mkt_user->id;
            $mc->limit_car = Input::get('limit_car') ? Input::get('limit_car') : 0;
            $mc->limit_order = Input::get('limit_order') ? Input::get('limit_order') : 0;
            $mc->pack_id = 0;
            $mc->discount = Input::get('discount') ? Input::get('discount') : 1;
            $mc->limit_book = Input::get('limit_book') ? Input::get('limit_book') : 0;
            $mc->limit_type = Input::get('limit_type') ? Input::get('limit_type') : 0;
            $mc->limit_desc = Input::get('limit_desc');
            $mc->exchange_method = Input::get('exchange_method',1);//新增 2018-11-16 sqq
            $mc->password = Input::get('password');//新增 2018-11-16 sqq
            $mc->ding_price = Input::get('ding_price');  //新增 2018-11-16 sqq
            $mc->item_id_num = Input::get('item_id_num');  //新增 2018-11-16 sqq
            $mc->save();
            //查看是否有 服务限制
            if (Input::get('pack_id_arr')) {
                $moo_ids = json_decode(Input::get('pack_id_arr'), 1);
                foreach ($moo_ids as $_m) {
                    $cpl = new CouponPackLimit();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_m;
                    $cpl->save();
                }
            }

            if (Input::get('pack_id')) {
                $moo_ids = json_decode(Input::get('pack_id'), 1);
                foreach ($moo_ids as $_m) {
                    $cpl = new CouponPack();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_m;
                    $cpl->save();
                }
            }

            //耗材
            if (Input::get('item_id_arr')) {
                $item_ids = json_decode(Input::get('item_id_arr'), 1);
                foreach ($item_ids as $_i) {
                    $cpl = new CouponItemLimit();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_i;
                    $cpl->created_at = Common::currentTimeString();
                    $cpl->updated_at = Common::currentTimeString();
                    $cpl->save();
                }
            }
            if (Input::get('item_id')) {
                $it_ids = json_decode(Input::get('item_id'), 1);
                foreach ($it_ids as $_it) {
                    $cpl = new CouponItem();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_it;
                    $cpl->created_at = Common::currentTimeString();
                    $cpl->updated_at = Common::currentTimeString();
                    $cpl->save();
                }
            }

            //耗材分类
            if (Input::get('item_class_id_arr')) {
                $item_ids = json_decode(Input::get('item_class_id_arr'), 1);
                foreach ($item_ids as $_i) {
                    $cpl = new CouponItemClassLimit();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_i;
                    $cpl->created_at = Common::currentTimeString();
                    $cpl->updated_at = Common::currentTimeString();
                    $cpl->save();
                }
            }
            if (Input::get('item_class_id')) {
                $it_ids = json_decode(Input::get('item_class_id'), 1);
                foreach ($it_ids as $_it) {
                    $cpl = new CouponItemClass();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_it;
                    $cpl->created_at = Common::currentTimeString();
                    $cpl->updated_at = Common::currentTimeString();
                    $cpl->save();
                }
            }

            //活动包
            if (Input::get('activity_id_arr')) {
                $item_ids = json_decode(Input::get('activity_id_arr'), 1);
                foreach ($item_ids as $_i) {
                    $cpl = new CouponActivityLimit();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_i;
                    $cpl->created_at = Common::currentTimeString();
                    $cpl->updated_at = Common::currentTimeString();
                    $cpl->save();
                }
            }
            if (Input::get('activity_id')) {
                $it_ids = json_decode(Input::get('activity_id'), 1);
                foreach ($it_ids as $_it) {
                    $cpl = new CouponActivity();
                    $cpl->coupon_base_info_id = $mc->id;
                    $cpl->pack_id = $_it;
                    $cpl->created_at = Common::currentTimeString();
                    $cpl->updated_at = Common::currentTimeString();
                    $cpl->save();
                }
            }

            //判断 如果超过10000张 直接脚本跑
//            if (Input::get('count') >= 10000) {
//                $ctt = new CouponsTempTable();
//                $ctt->coupon_base_info_id = $mc->id;
//                $ctt->code_type = Input::get('code_type');
//                $ctt->code = Input::get('code');
//                $ctt->count = Input::get('count');
//                $ctt->status = 1;
//                $ctt->created_by = $mkt_user->id;
//                $ctt->save();
//                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("coupon_base_info_id" => $mc->id, 'msg' => '脚本正在执行，稍后查询'));
//                break;
//            }
            $input = array(
                'coupon_base_info_id' => $mc->id,
                'status' => 1,
                'received_user_id' => 0,
                'used_user_id' => 0,
                'created_at' => date('Y-m-d H:i:s', time()),
                'updated_at' => date('Y-m-d H:i:s', time()),
            );

            $num = intval(Input::get('count'));
            $limit = 5000;
            $bag = array();
            for ($i = 0, $j = 0; $i < $num; $i++) {
                //生成统一的优惠码
                if (Input::get('code_type') == 1) { //1 代表 随机码
                    $bonus_arr = Helper::getStr($mc->id, $mkt_user->id);
                    if ((int)Input::get('type') == 1) {
                        $bonus_sn = 'jm' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                    }
                    if ((int)Input::get('type') == 2) {
                        $bonus_sn = 'fw' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                    }
                    if ((int)Input::get('type') == 3) {
                        $bonus_sn = 'sw' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                    }
                    if ((int)Input::get('type') == 4) {
                        $bonus_sn = 'fj' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                    }
                    if ((int)Input::get('type') == 5) {
                        $bonus_sn = 'fd' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                    }
                } else {
                    $bonus_sn = Input::get('code');
                }
                $input['code'] = $bonus_sn;

                $count = count($bag);
                if ($count === $limit OR $count === ($num - 1)) {
                    if ($num - 1 != 0) {
                        DB::table('coupons')->insert($bag);
                    }
                    $bag = array();
                }
                $bag[] = $input;
                $j++;
            }
            if (count($bag) > 0) {
                DB::table('coupons')->insert($bag);
                $bag = array();
            }

            //创建优惠券成功记录
            $coupon_ids = CouponIncrement::where('coupon_base_info_id', Input::get('id'))->where('status',1)->first();
            if(!is_null($coupon_ids)){
                $type = 2;
            }else{
                $type = 1;
            }
            try {
                $coupon = new CouponIncrement();
                $coupon->coupon_base_info_id = $mc->id;
                $coupon->count = Input::get('count', 0);
                $coupon->type = $type;
                $coupon->created_at = Common::currentTimeString();
                $coupon->updated_at = Common::currentTimeString();
                $coupon->created_by = $mkt_user->id;
                $coupon->num_type = Input::get('num_type', 0);
                $coupon->status = 1;
                $coupon->save();
            }catch (Exception $e) {
                Log::error("error", array("system" => "mkt", "event" => "coupon_create", 'input' => Input::all(), "exception" => $e));
                return $response = Lang::get("mkt_error.coupon_save_error_510002");
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("coupon_base_info_id" => $mc->id));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_create", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      dx
     * @DateTime:    2016-03-9 09:59:41
     * @Description: 创建优惠活动
     * http://www.activity.com/v1/mkt/coupon/activity_create?token=c6b0ab3cfb66b3c6d9fd57a28488f2f8&name=%E6%B5%8B%E8%AF%95&status=1&product_type=1&begin_date=2018-06-04%2012:10:22&end_date=2018-07-20%2012:10:22&banner_url=www.baidu.com&type=0
     */
    public function activity_create()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required|max:25',
                //'desc' => 'required|max:200',
                'status' => 'required|max:200',
                'product_type' => 'required',
                'begin_date' => 'required',
                'end_date' => 'required',
                'banner_url' => 'required',
                'type' => 'required',
                // 'coupon_base_info_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            //判断活动重复添加
            $check_activity_coupon = ActivityBaseInfo::where('name', Input::get('name'))->where('product_type', Input::get("product_type"))->where('status', 1)->first();
            if (!is_null($check_activity_coupon)) {
                $response = Lang::get("mkt_error.mkt_coupon_activity_exit_error_310002");
                break;
            }
            //上传优惠活动图片
            $banner_url = "";
            if (Input::hasFile('banner_url')) {
                $icon_file = Input::file('banner_url');
                $filename = CouponBaseInfo::getImageName();
                $icon_file->move(Config::get('config.activity_file'), $filename);
                $banner_url = $filename;
            }
            try {
                $abi = new ActivityBaseInfo();
                $abi->name = Input::get('name');
                $abi->desc = Input::get('desc');
                $abi->product_type = Input::get('product_type');
                $abi->begin_date = date('Y-m-d', strtotime(Input::get('begin_date'))) . ' 00:00:00';
                $abi->end_date = date('Y-m-d', strtotime(Input::get('end_date'))) . ' 23:59:59';
                $abi->type = Input::get('type');
                $abi->banner_url = $banner_url;
                $abi->status = Input::get('status');
                $abi->created_by = $mkt_user->id;
                $abi->award_group = is_numeric(Input::get("award_group")) ? Input::get("award_group") : 0;
                $abi->save();

                if ($abi->type == 1) {//抽奖的优惠券
                    if (empty(Input::get('award_group'))) {
                        $response = Lang::get("mkt_error.mkt_coupon_activity_award_error_310005");
                        break;
                    }
                    $activity_coupon_info = ActivityAward::where('award_group_id', Input::get("award_group"))->where("prize_type", 0)->get();
                    if (count($activity_coupon_info) > 0) {
                        foreach ($activity_coupon_info as $_c) {
                            $aci = new ActivityCouponInfo();
                            $aci->activity_id = $abi->id;
                            $aci->coupon_base_info_id = $_c->prize_id;
                            $aci->status = 1;
                            $aci->save();
                        }
                    }
                } else {
                    //活动绑定优惠券
                    $c_i = Input::get('coupon_base_info_id');
                    if (!empty($c_i)) {
                        $coupon_ids = array_unique(explode(",", rtrim(Input::get('coupon_base_info_id'), ','))); //切割去重
                        foreach ($coupon_ids as $_c) {
                            $aci = new ActivityCouponInfo();
                            $aci->activity_id = $abi->id;
                            $aci->coupon_base_info_id = $_c;
                            $aci->status = 1;
                            $aci->save();
                        }
                    }
                }

                //创建站内信
                $notice = ScNotice::InsertCouponNotice($abi->id, Input::get('name'), Input::get('desc'), Input::get('product_type'), $abi->begin_date, $abi->end_date, Input::get('type'), Input::get('status'), $mkt_user->id);

            } catch (Exception $e) {
                Log::error("error", array("system" => "mkt", "event" => "activity_create", 'input' => Input::all(), "exception" => $e));
                return $response = Lang::get("mkt_error.mkt_coupon_activity_create_error_310001");
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("activity_base_info_id" => $abi->id));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "activity_create", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:    2016-03-11 11:38:37
     * @Description: 优惠活动列表
     */
    public function activity_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page" => 'integer',
                "page_size" => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 1);

            $activites = ActivityBaseInfo::orderBy('id', 'desc');
            // $activites = ActivityBaseInfo::leftjoin('activity_coupon_info','activity_base_info.id','=','activity_coupon_info.activity_id')
            //     ->leftjoin('coupon_base_info','activity_coupon_info.coupon_base_info_id','=','coupon_base_info.id')
            //     ->select('activity_base_info.name as activity_name','activity_base_info.status','activity_base_info.product_type','activity_base_info.begin_date',
            //         'activity_base_info.end_date','activity_coupon_info.coupon_base_info_id as chosed_coupon_id', 'activity_base_info.id')
            //     ->orderBy('activity_base_info.id','desc');


            if (Input::get("product_type") == 1 || Input::get('product_type') == 2) { //发放方式 1-线上 2-线下
                $activites->where("product_type", Input::get("product_type"));
            }
            if (Input::get("status") != "") {
                $activites->where("status", Input::get("status"));
            }
            if (Input::get("begin_date")) {
                // $activites->where("begin_date",Input::get("begin_date"));
                $activites->whereRaw('begin_date >= ' . "'" . Input::get("begin_date") . "'");
            }
            if (Input::get("end_date")) {
                // $activites->where("end_date",Input::get("end_date"));
                $activites->whereRaw('end_date <=' . "'" . Input::get("end_date") . "'");
            }
            if (Input::get("name") != "") {
                $activites->where('name', 'LIKE', '%' . Input::get('name') . '%');
            }

            $count = $activites->count();
            $activites = $activites->skip($page_size * ($page - 1))->take($page_size)->get();
            $arr_activites = array();
            foreach ($activites as $_a) {
                if ($_a->type == 1) {
                    $award_group = ActivityAwardGroup::where('id', $_a->award_group)->first();
                    $coupon_id = $_a->award_group;
                    $coupon_name = isset($award_group->name) ? $award_group->name : '';

                } else {
                    $activity_coupon_info = ActivityCouponInfo::where('activity_id', $_a->id)->where('status', 1)->get();
                    // print_r($activity_coupon_info);
                    $coupon_id = "";
                    $coupon_name = "";
                    if (count($activity_coupon_info) > 0) {
                        foreach ($activity_coupon_info as $a) {
                            $coupon_id .= $a->coupon_base_info_id . ',';
                            $coupon_base_info = CouponBaseInfo::where('id', $a->coupon_base_info_id)->first();
                            $coupon_name .= $coupon_base_info->name . ',';
                        }
                    }
                }


                $arr_activites[] = array(
                    "id" => $_a->id,
                    "name" => $_a->name,
                    "product_type" => ActivityBaseInfo::$product_type[$_a->product_type],
                    "status" => ActivityBaseInfo::$status[$_a->status],
                    "types" => ActivityBaseInfo::$types[$_a->type],
                    "activity_type" => $_a->type,
                    "begin_date" => $_a->begin_date,
                    "end_date" => $_a->end_date,
                    "coupon_base_info_id" => rtrim($coupon_id, ','),
                    "coupon_name" => rtrim($coupon_name, ','),
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count" => $count, "activites" => $arr_activites));

        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "activity_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:    2016-06-21 11:38:37
     * @Description: 优惠券列表
     */
    public function coupon_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page" => 'integer',
                "page_size" => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 1);

            $coupon = CouponBaseInfo::orderBy('id', 'desc');


            if (Input::get("code_type") == 1 || Input::get('code_type') == 2) { //券码类型 1-随机码 2-统一码
                $coupon->where("code_type", Input::get("code_type"));
            }
            if (Input::get("status") != "") {
                $coupon->where("status", Input::get("status"));
            }
            // if(Input::get("begin_date")){
            //     $coupon->whereRaw('begin_date >= '."'".Input::get("begin_date")."'");
            // }
            // if(Input::get("end_date")){
            //     $coupon->whereRaw('end_date <='."'".Input::get("end_date")."'");
            // }
            if (Input::get("type") != "") {
                $coupon->where("type", Input::get("type"));
            }
            if (Input::get("name") != "") {
                $coupon->where('name', 'LIKE', '%' . Input::get('name') . '%');
            }

            $count = $coupon->count();
            $coupon_obj = $coupon->skip($page_size * ($page - 1))->take($page_size)->get();
            $arr_coupon = array();
            foreach ($coupon_obj as $_a) {
                $activity_coupon_info = ActivityCouponInfo::where('coupon_base_info_id', $_a->id)->where('status', 1)->first();
                $activity_id = "";
                $activity_name = "";
                if (count($activity_coupon_info) > 0) {
                    $activity_id = $activity_coupon_info->activity_id;
                    $activity_base_info = ActivityBaseInfo::where('id', $activity_id)->first();
                    $activity_name = $activity_base_info->name;
                }
                if ($_a->date_type == 1) {
                    $begin_date = "";
                    $end_date = "";
                } else {
                    $begin_date = $_a->begin_date;
                    $end_date = $_a->end_date;
                }
                // $product=ProductPackage::find($_a->pack_id);
                $pack = CouponPack::leftJoin("product_package", "product_package.id", "=", "coupon_pack.pack_id")->where("coupon_pack.coupon_base_info_id", $_a->id)->select("product_package.id", "product_package.name")->get();
                $limit_pack = CouponPackLimit::leftJoin("product_package", "product_package.id", "=", "coupon_pack_limit.pack_id")->where("coupon_pack_limit.coupon_base_info_id", $_a->id)->select("product_package.id", "product_package.name")->get();
                $count = CouponIncrement::where('coupon_base_info_id',$_a->id)->where('status',1)->sum('count');
                $arr_coupon[] = array(
                    "id" => $_a->id,
                    "name" => $_a->name,
                    "code_type" => CouponBaseInfo::$code_type[$_a->code_type],
                    "type" => CouponBaseInfo::$type[$_a->type],
                    "status" => ActivityBaseInfo::$status[$_a->status],
                    "amount" => $_a->amount,
                    "count" => $count,
                    "limit_amount" => $_a->limit_amount,
                    "limit_order" => $_a->limit_order,
                    "limit_car" => $_a->limit_car,
                    "created_at" => date("Y-m-d H:i:s", strtotime($_a->created_at)),
                    "date_type" => $_a->date_type,
                    "begin_date" => $begin_date,
                    "end_date" => $end_date,
                    "date_num" => $_a->date_num,
                    "activity_id" => $activity_id,
                    "activity_name" => $activity_name,
                    "discount" => $_a->discount,
                    "limit_book" => $_a->limit_book,
                    "limit_type" => $_a->limit_type,
                    // 'pack_id'=>$_a->pack_id,
                    // 'pack_name'=>isset($product)?$product->name:"",
                    "pack" => $pack,
                    "limit_pack" => $limit_pack,
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count" => $count, "coupon" => $arr_coupon));

        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:    2016-06-22 09:14:27
     * @Description: 修改保存活动
     * http://www.activity.com/v1/mkt/coupon/edit_activity?token=c6b0ab3cfb66b3c6d9fd57a28488f2f8&name=测试&status=1&product_type=1&begin_date=2018-06-04%2012:10:22&end_date=2018-07-20%2012:10:22&banner_url=www.baidu.com&type=0&desc=哈哈哈&id=70
     */
    public function edit_activity()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => "required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $activity = ActivityBaseInfo::where('id', Input::get('id'))->first();
            if (empty($activity)) {
                $response = Lang::get("mkt_error.activity_not_exit_error_410001");
                break;
            }
            try {
                $activity->name = Input::get('name');
                $activity->desc = Input::get('desc');
                $activity->type = Input::get('type');
                $activity->status = Input::get('status');
                $activity->product_type = Input::get('product_type');
                $activity->begin_date = date('Y-m-d', strtotime(Input::get('begin_date'))) . ' 00:00:00';
                $activity->end_date = date('Y-m-d', strtotime(Input::get('end_date'))) . ' 23:59:59';
                $activity->award_group = is_numeric(Input::get("award_group")) ? Input::get("award_group") : 0;
                $activity->save();

                ActivityCouponInfo::where('activity_id', Input::get('id'))->delete();
                if (Input::get('type') == 1) {
                    if (empty(Input::get('award_group'))) {
                        $response = Lang::get("mkt_error.mkt_coupon_activity_award_error_310005");
                        break;
                    }
                    $activity_coupon_info = ActivityAward::where('award_group_id', Input::get("award_group"))->where("prize_type", 0)->get();
                    if (count($activity_coupon_info) > 0) {
                        foreach ($activity_coupon_info as $_c) {
                            $aci = new ActivityCouponInfo();
                            $aci->activity_id = Input::get('id');
                            $aci->coupon_base_info_id = $_c->prize_id;
                            $aci->status = 1;
                            $aci->save();
                        }
                    }
                } else {
                    $c_i = Input::get('coupon_ids');
                    if (!empty($c_i)) {
                        $coupon_ids = array_unique(explode(",", rtrim(Input::get('coupon_ids'), ',')));
                        // if(count($coupon_ids) > 0 ){
                        foreach ($coupon_ids as $c) {
                            $aci = new ActivityCouponInfo();
                            $aci->activity_id = Input::get('id');
                            $aci->coupon_base_info_id = $c;
                            $aci->status = 1;
                            $aci->save();
                        }
                        // }
                    }
                }
                //修改优惠活动站内信
                $notice = ScNotice::UpdateCouponNotice($activity->id, Input::get('name'), Input::get('desc'), Input::get('product_type'), $activity->begin_date, $activity->end_date, Input::get('type'), Input::get('status'), $mkt_user->id);

                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("id" => $activity->id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "mkt", "event" => "edit_activity", 'input' => Input::all(), "exception" => $e));
                $response = Lang::get("mkt_error.activity_save_error_410002");
                break;
            }


        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "edit_activity", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:    2016-06-22 14:14:27
     * @Description: 活动详情页
     */
    public function activity_show()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => "required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $activity = ActivityBaseInfo::where('id', Input::get('id'))->first();
            if (empty($activity)) {
                $response = Lang::get("mkt_error.activity_not_exit_error_410001");
                break;
            }
            $activity_coupon_info = ActivityCouponInfo::where('activity_id', $activity->id)->where('status', 1)->get()->toArray();
            $coupons_info = array();
            if ($activity_coupon_info) {
                foreach ($activity_coupon_info as $_a_c_i) {
                    $coupon_base_info = array();
                    $coupon_base_info = CouponBaseInfo::where('id', $_a_c_i['coupon_base_info_id'])->first()->toArray();
                    $coupons_info[] = $coupon_base_info;
                    // $coupons_info[$_a_c_i['activity_id']]['activity_id'] = $_a_c_i['activity_id'];
                    // $coupons_info[$_a_c_i['activity_id']]['coupon_obj'][] = $coupon_base_info;
                }
            }
            $arr_award_info = array();
            $aag = ActivityAwardGroup::find($activity->award_group);
            if ($aag) {
                $activity_coupon_info = ActivityAward::where('award_group_id', $aag->id)->get();
                foreach ($activity_coupon_info as $v) {
                    $activity_order = ActivityOrder::where('award_id', $v->id)->where('activity_id', $activity->id)->whereNotNull('user_id');
                    $probability = $v->probability * 100;
                    $v->probability = $probability . '%';
                    $v->winning_number = $activity_order->count();
                    $v->now_number = $activity_order->whereBetween('created_at', [date('Y-m-d', time()) . ' ' . '00:00:00', date('Y-m-d', time()) . ' ' . '23:59:59'])->count();
                }
                $arr_award_info = array(
                    "id" => $aag->id,
                    "name" => $aag->name,
                    "status" => ActivityAwardGroup::$status[$aag->status],
                    "created_byname" => isset($aag->created_byname) ? $aag->created_byname->real_name : '',
                    "updated_at" => $aag->updated_at . "",
                    "created_at" => $aag->created_at . "",
                    "awards_count" => sizeof($activity_coupon_info),
                    "awards" => $activity_coupon_info,
                );
            } else {
                $arr_award_info = null;
            }
            $coupon_situation = array();
            $coupon_other_info = array();
            if ($activity->type != 1) {
                $coupons_infos = $coupons_info;
                if (count($coupons_info) > 0) {
                    $coupon_ids = '';
                    foreach ($coupons_info as $_i) {
                        $temp = array();
                        $temp['name'] = $_i['name'];
                        $coupon_received = Coupons::where('status', 2)->where('coupon_base_info_id', $_i['id'])->count();
                        $temp['received'] = $coupon_received;
                        $temp['count'] = $_i['count'];
                        $coupon_ids .= $_i['id'] . ',';
                        $coupon_situation[] = $temp;
                    }
                    $coupon_ids = explode(',', rtrim($coupon_ids, ','));
                    // $coupon_received_user_count = DB::select('SELECT COUNT(DISTINCT(received_user_id)) as count FROM coupons WHERE coupon_base_info_id IN ('.$coupon_ids.') AND received_user_id != 0 ');
                    $coupon_received_user_count = Coupons::where('received_user_id', '!=', 0)->whereIn('coupon_base_info_id', $coupon_ids)->select('received_user_id')->distinct()->count();
                    $register_user = Users::where('status', 1)->where('register_source_id', 1)->where('type', 1)->where('created_at', '>=', $activity->begin_date)->where('created_at', '<=', $activity->end_date)->count();
                    $coupon_other_info['received_user_count'] = $coupon_received_user_count;
                    $coupon_other_info['register_user'] = $register_user;
                }
            } else {
                $coupons_infos = array();
            }
            $temp_arr = array("activity_base_info" => $activity, "arr_award_info" => $arr_award_info, "coupon_info" => $coupons_infos, 'coupon_situation' => $coupon_situation, 'coupon_other_info' => $coupon_other_info);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "activity_show", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:    2016-06-22 14:14:27
     * @Description: 修改活动--优惠券列表--开启 并且 未被 添加的优惠券
     */
    public function edit_activity_coupon()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page" => 'integer',
                "page_size" => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 1);

            $coupons = CouponBaseInfo::where('status', 1)->where('num_type', 0)
                ->whereNotIn('id', function ($q) {
                    $q->select('coupon_base_info_id')->from('activity_coupon_info')->where('status', 1);
                })
                ->whereNotIn('id', function ($q) {
                    $q->select('prize_id')->from('activity_award');
                });
            if (Input::get("name") != "") {
                $coupons->where('name', 'LIKE', '%' . Input::get('name') . '%');
            }

            $count = $coupons->count();
            $coupon_obj = $coupons->skip($page_size * ($page - 1))->take($page_size)->get();
            foreach ($coupon_obj as $_c) {
                // $product=ProductPackage::find($_c->pack_id);
                $pack = CouponPack::leftJoin("product_package", "product_package.id", "=", "coupon_pack.pack_id")->where("coupon_pack.coupon_base_info_id", $_c->id)->select("product_package.id", "product_package.name")->get();
                $limit_pack = CouponPackLimit::leftJoin("product_package", "product_package.id", "=", "coupon_pack_limit.pack_id")->where("coupon_pack_limit.coupon_base_info_id", $_c->id)->select("product_package.id", "product_package.name")->get();

                $_c->pack = $pack;
                $_c->limit_pack = $limit_pack;
            }
            // $other_coupons =  DB::select('SELECT * FROM coupon_base_info WHERE id NOT IN (SELECT coupon_base_info_id FROM activity_coupon_info WHERE STATUS = 1) and status = 1');

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('count' => $count, 'other_coupons' => $coupon_obj));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "edit_activity_coupon", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      dx
     * @DateTime:    2016-06-22 09:14:27
     * @Description: 修改优惠券-保存
     */
    public function edit_coupon()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => "required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $coupon = CouponBaseInfo::where('id', Input::get('id'))->first();
            if (empty($coupon)) {
                $response = Lang::get("mkt_error.coupon_not_exit_error_510001");
                break;
            }

            $date_num = trim(Input::get('date_num'));
            if ($date_num) {
                $date_num = trim(Input::get('date_num'));
            } else {
                $date_num = 0;
            }
            $begin_date = Input::get('begin_date');
            if ($begin_date) {
                $begin_date = Input::get('begin_date');
            }
            $end_date = Input::get('end_date');
            if ($end_date) {
                $end_date = Input::get('end_date');
                //检测优惠券是否可以创建
                $today = date("Y-m-d");
                if ($today > $end_date) {
                    $response = Lang::get("mkt_error.mkt_coupon_date_error_310003");
                    break;
                }
            }
            if(Input::get('exchange_method') == 2 && Input::get('password') == ""){
                $response = Lang::get("mkt_error.coupon_password_not_exit_error_510006");
                break;
            }
            try {
                $coupon->name = Input::get('name');
                $coupon->desc = Input::get('desc');
                $coupon->status = Input::get('status');
                $coupon->limit_desc = Input::get('limit_desc');
                $coupon->exchange_method = Input::get('exchange_method',1);//新增 2018-11-16 sqq
                $coupon->password = Input::get('password');//新增 2018-11-16 sqq
                $coupon->created_by = $mkt_user->id;
                $coupon->save();

                $response = array('code' => 0, 'msg' => 'ok', 'result' => array("id" => $coupon->id));
            } catch (Exception $e) {
                Log::error("error", array("system" => "mkt", "event" => "edit_coupon", 'input' => Input::all(), "exception" => $e));
                $response = Lang::get("mkt_error.coupon_save_error_510002");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "edit_coupon", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      dx
     * @DateTime:    2016-06-24 10:14:27
     * @Description: 优惠券详情页
     */
    public function coupon_show()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => "required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $coupon = CouponBaseInfo::where('id', Input::get('id'))->first();
            if (empty($coupon)) {
                $response = Lang::get("mkt_error.coupon_not_exit_error_510001");
                break;
            }
            $activity_coupon_info = ActivityCouponInfo::leftjoin('activity_base_info', 'activity_coupon_info.activity_id', '=', 'activity_base_info.id')
                ->where('activity_coupon_info.coupon_base_info_id', $coupon->id)
                ->where('activity_coupon_info.status', 1)
                ->select(array('activity_base_info.name', 'activity_coupon_info.activity_id'))
                ->first();

            $coupon_received = Coupons::where('received_user_id', '!=', 0)->where('used_user_id', 0)->where('coupon_base_info_id', $coupon->id)->count();
            $coupon_used = Coupons::where('status', 4)->where('coupon_base_info_id', $coupon->id)->count();
            $coupon_surplus = Coupons::where('received_user_id', 0)->where('used_user_id', 0)->where('coupon_base_info_id', $coupon->id)->count();
            $coupon_statistics = array();
            $coupon_statistics = array(
                'coupon_received' => $coupon_received,
                'coupon_used' => $coupon_used,
                'coupon_surplus' => $coupon_surplus
            );
            // $product_package = ProductPackage::select('id','name')
            //     ->where('id',$coupon->pack_id)
            //     ->first();
            $product_package = CouponPack::leftjoin("product_package", "product_package.id", "=", "coupon_pack.pack_id")->select("product_package.id", "product_package.name")->where("coupon_pack.coupon_base_info_id", $coupon->id)->get();

            $limit_package = CouponPackLimit::leftjoin("product_package", "product_package.id", "=", "coupon_pack_limit.pack_id")->select("product_package.id", "product_package.name")->where("coupon_pack_limit.coupon_base_info_id", $coupon->id)->get();

            $temp_arr = array("coupon_base_info" => $coupon, "activity_info" => $activity_coupon_info, 'coupon_statistics' => $coupon_statistics, 'product_package' => $product_package, "limit_package" => $limit_package);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_show", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      dx
     * @DateTime:    2016-06-24 11:38:37
     * @Description: 优惠券使用情况
     */
    public function coupon_used_summary()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                "page" => 'integer',
                "page_size" => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 1);

            // $coupon = Coupons::with('users')->where('coupon_base_info_id',Input::get('id'))->orderBy('id','asc');

            $coupon = Coupons::leftJoin('users', "users.id", "=", "coupons.received_user_id")->where('coupons.coupon_base_info_id', Input::get('id'))->select("coupons.*", "users.phone")->orderBy('coupons.id', 'asc');
            if (Input::get("start_time") != "") {
                $coupon->where('coupons.get_time', '>', Input::get('start_time'));
            }
            if (Input::get("end_time") != "") {
                $coupon->where('coupons.get_time', '<=', Input::get('end_time'));
            }
            if (Input::get("code") != "") {
                $coupon->where('coupons.code', 'LIKE', '%' . Input::get('code') . '%');
            }
            if (Input::get("phone") != "") {
                $coupon->where('users.phone', 'LIKE', '%' . Input::get('phone') . '%');
            }
            if (Input::get("car_no") != "") {
                $coupon->where('coupons.used_car_no', 'LIKE', '%' . Input::get('car_no') . '%');
            }

            $count = $coupon->count();
            $coupons = $coupon->skip($page_size * ($page - 1))->take($page_size)->get();
            $arr_c = array();
            //0:服务单 1：洗车单 2：零售单
            foreach ($coupons as $_a) {
                $check_coupon_order_info = CouponOrderInfo::where('status', 1)->where('coupon_id', $_a->id)->first();
                if (!is_null($check_coupon_order_info)) {
                    $order = Orders::with('maintenanceShops')->where('order_id', $check_coupon_order_info->order_id)->first();
                    if (is_null($order)) {
//                        $order = CarWashOrder::with('maintenanceShops')->where('order_id', $check_coupon_order_info->order_id)->first();
//                        if (!is_null($order)) {
//                            $order->is_wash = 1;  //洗车单
//                        }
                        $order->is_wash = '';
                    }else{
                        $order->is_wash =  $order->order_type == 1 ? 0 : 2;
                    }
                }else{
                    $check_coupon_order_info = CouponCarWashOrderInfo::where('status', 1)->where('coupon_id', $_a->id)->first();
                    if(!is_null($check_coupon_order_info)){
                        $order = CarWashOrder::with('maintenanceShops')->where('order_id', $check_coupon_order_info->order_id)->first();
                        if(!is_null($order)){
                            $order->is_wash = 1;  //洗车单
                        }else{
                            $order->is_wash = '';
                        }
                    }
                }
                $award = ActivityAward::where('prize_id', $_a->coupon_base_info_id)->first();
                if ($award) {
                    $award_group = ActivityAwardGroup::where('id', $award->award_group_id)->first();
                }
                $arr_c[] = array(
                    "id" => $_a->id,
                    "code" => $_a->code,
                    "received_user_id" => $_a->received_user_id,
                    "received_user" => $_a->phone,
                    "get_time" => $_a->get_time,
                    "order_id" => empty($check_coupon_order_info) ? "" : $check_coupon_order_info->order_id,
                    'award_group_name' => isset($award_group->name) ? $award_group->name : '',
                    'car_no' => $_a->used_car_no,
                    "use_time" => $_a->use_time,
                    "order_type" => isset($order->is_wash) ? $order->is_wash : '',
                    "order_shop_id" => isset($order->shop_id) ? $order->shop_id : '',
                    "order_shop_name" => isset($order['maintenanceShops']->name) ? $order['maintenanceShops']->name : '',
                );
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count" => $count, "coupon_used_summary" => $arr_c));

        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_used_summary", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      dx
     * @DateTime:    2016-06-27 11:38:37
     * @Description: 优惠活动导出list
     */
    public function activity_excel_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            $activity = ActivityBaseInfo::where('id', Input::get('id'))->first();
            $activity_coupon_list = array();
            if ($activity) {
                $activity_relation = ActivityCouponInfo::where('activity_id', $activity->id)->where('status', 1)->get();
                if ($activity_relation) {
                    foreach ($activity_relation as $_r) {

                        $coupons_relation = CouponBaseInfo::leftjoin('coupons', 'coupon_base_info.id', '=', 'coupons.coupon_base_info_id')
                            ->where('coupon_base_info.id', $_r->coupon_base_info_id)
                            ->select(array('coupon_base_info.id', 'coupon_base_info.name', 'coupon_base_info.type', 'coupon_base_info.amount', 'coupon_base_info.limit_amount', 'coupon_base_info.date_type', 'coupon_base_info.begin_date'
                            , 'coupon_base_info.end_date', 'coupon_base_info.date_num', 'coupon_base_info.limit_order', 'coupons.code', 'coupon_base_info.discount', 'coupon_base_info.limit_book', 'coupon_base_info.limit_car', 'coupon_base_info.limit_type'))->first();
                        $package = CouponPack::leftjoin("product_package", "product_package.id", "=", "coupon_pack.pack_id")->select("product_package.id", "product_package.name")->where("coupon_pack.coupon_base_info_id", $coupons_relation->id)->get();
                        $limit_package = CouponPackLimit::leftjoin("product_package", "product_package.id", "=", "coupon_pack_limit.pack_id")->select("product_package.id", "product_package.name")->where("coupon_pack_limit.coupon_base_info_id", $coupons_relation->id)->get();
                        $activity_coupon_list[] = array(
                            "coupon_id" => $coupons_relation->id,
                            "coupon_name" => $coupons_relation->name,
                            "type" => $coupons_relation->type,
                            "amount" => $coupons_relation->amount,
                            "limit_amount" => $coupons_relation->limit_amount,
                            "date_type" => $coupons_relation->date_type,
                            "begin_date" => $coupons_relation->begin_date,
                            "end_date" => $coupons_relation->end_date,
                            "date_num" => $coupons_relation->date_num,
                            "limit_order" => $coupons_relation->limit_order,
                            "code" => $coupons_relation->code,
                            "activity_id" => $activity->id,
                            "activity_name" => $activity->name,
                            "activity_begin_date" => $activity->begin_date,
                            "activity_end_date" => $activity->end_date,
                            "product_type" => $activity->product_type,
                            "discount" => $coupons_relation->discount,
                            "limit_book" => $coupons_relation->limit_book,
                            "limit_car" => $coupons_relation->limit_car,
                            "limit_type" => $coupons_relation->limit_type,
                            "pack" => $package,
                            "limit_pack" => $limit_package,
                        );
                    }
                }
            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('activity_relation' => $activity_coupon_list));

        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "activity_excel_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      kc
     * @DateTime:    2016-11-23 14:03:37
     * @Description: 服务抵用券所使用的产品包
     */
    public function service_product_package()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            // $product_package = ProductPackageCity::join('product_package','product_pack_city.pack_id','=','product_package.id')
            $product_package = ProductPackage::select([
                'product_package.id',
                'product_package.name',
            ]);
            if (Input::get("place")) {
                $product_package = $product_package->where('product_package.place', Input::get("place"));
            } else {
                $product_package = $product_package->where('product_package.place', 2);
            }

            $product_package = $product_package->where('product_package.status', 1)
                // ->where('product_pack_city.city_id',1)
                // ->where('product_pack_city.status',1)
                ->get();
            //$response = array('code' => 0, 'msg' => 'ok', 'result' => $product_package);
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('package' => $product_package, 'type' => 'package'));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "service_product_package", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-06-02 14:31:51
     * @Description: 通过用户手机号发送优惠券的接口
     */
    public function send_conpous()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'phone' => 'required',
                //'car_no' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $user = Users::where("phone", Input::get("phone"))->where("status", 1)->first();
            if (!$user) {
                $response = Lang::get("scs_error.user_error_21009");
                break;
            }
            $coupon_base_info = DB::table('coupon_base_info')->where('id', Input::get("id"))->where('status', 1)->first();
            if (!$coupon_base_info) {
                $response = Lang::get("scs_error.coupon_base_error_90022");
                break;
            }
            if (!(Input::get("car_no")) && $coupon_base_info->limit_car == 1) {
                $response = Lang::get("scs_error.mkt_ccoupon_car_no_not_error_210013");
                break;
            }
            $coupons = DB::table("coupons")->select('id')
                ->where('coupon_base_info_id', Input::get("id"))
                ->where('get_time', '0000-00-00 00:00:00')
                ->where('use_time', '0000-00-00 00:00:00')
                ->where('received_user_id', 0)
                ->where('used_user_id', 0)
                ->where('status', 1)
                ->first();
            if (!is_null($coupons)) {
                if ($coupon_base_info->date_type == 1) {
                    $begin_date = date("Y-m-d H:i:s", time());
                    $end_date = date("Y-m-d", strtotime("+" . $coupon_base_info->date_num . " day"));
                } else {
                    //$begin_date = $coupon_base_info->begin_date;
                    $begin_date = date("Y-m-d H:i:s", time());
                    $end_date = null;
                }
                DB::table("coupons")->where('id', $coupons->id)->update(array("received_user_id" => $user->id, 'get_time' => $begin_date, 'end_date' => $end_date, 'status' => 2, 'used_car_no' => Input::get("car_no")));
            } else {
                $response = Lang::get("scs_error.coupon_error_90021");
                break;
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('coupon_id' => $coupons->id));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "send_conpous", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 12:04:06
     * @Description: 优惠券城市配置
     */
    public function city_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'coupon_base_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $pas = CouponCity::where("coupon_base_id", Input::get('coupon_base_id'))->where("status", 1)->get();
            $citys = array();
            foreach ($pas as $_pas) {
                $citys[] = $_pas->city_id;
            }

            $all_cit = DB::select("select rct.id,rct.name,rpt.id rid ,rpt.`name` p_name from resource_city_type rct LEFT JOIN resource_city rc on rc.id=rct.id
                    LEFT JOIN resource_province_type rpt on rpt.id=rc.province_id where rct.`status`=1");
            foreach ($all_cit as $_r) {
                if (isset($resource_arr[$_r->rid])) {
                    $temparr = $resource_arr[$_r->rid];
                    $temparr["item"][] = $_r;
                    $resource_arr[$_r->rid] = $temparr;
                } else {
                    $resource_arr[$_r->rid] = array(
                        'r_id' => $_r->rid,
                        'name' => $_r->p_name,
                        'item' => array($_r),
                    );
                }
            }
            $resource_arr = array_values($resource_arr);
            foreach ($resource_arr as $ra) {
                foreach ($ra['item'] as $item) {
                    if (in_array($item->id, $citys)) {
                        $item->status = 1;
                    } else {
                        $item->status = 0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('city_list' => $resource_arr));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "city_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 13:57:24
     * @Description: 优惠券的城市保存
     */
    public function save_citys()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'coupon_base_id' => 'required',
                'city_ids' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $city_ids = json_decode(Input::get('city_ids'));
            CouponCity::where("coupon_base_id", Input::get('coupon_base_id'))->where("status", 1)->update(array('status' => 0));
            foreach ($city_ids as $_c) {
                $pas = new CouponCity();
                $pas->coupon_base_id = Input::get('coupon_base_id');
                $pas->city_id = $_c;
                $pas->created_by = $mkt_user->id;
                $pas->save();
            }
            /**
             * 修改城市适配的时候，不修改当前城市下所有门店  20170925 赵洋
             */
//            $ms=MaintenanceShops::whereIn('city_id',$city_ids)->where('status',1)->get();
//            CouponShop::where('coupon_base_id',Input::get('coupon_base_id'))->where('status',1)->update(array('status'=>0));
//            foreach($ms as $_ms){
//                $pas=new CouponShop();
//                $pas->coupon_base_id = Input::get('coupon_base_id');
//                $pas->shop_id = $_ms->id;
//                $pas->created_by = $mkt_user->id;
//                $pas->save();
//            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("coupon_base_id" => Input::get('coupon_base_id')));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "save_citys", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 14:39:52
     * @Description: 优惠券适用的门店
     */
    public function shop_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'coupon_base_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            $pas = CouponCity::where("coupon_base_id", Input::get('coupon_base_id'))->where("status", 1)->get();
            $shop_ids = CouponShop::where('coupon_base_id', Input::get('coupon_base_id'))->where('status', 1)->select("shop_id")->get()->toArray();
            $shop_ids = array_column($shop_ids, 'shop_id');
            $citys = array();
            foreach ($pas as $_pas) {
                // $ms=MaintenanceShops::where('city_id',$_pas->city_id)->where('status',1)->select('id','name')->get();
                $ms = MaintenanceShops::leftJoin("resource_region", "resource_region.id", "=", "maintenance_shops.region_id")->where('maintenance_shops.city_id', $_pas->city_id)->where('maintenance_shops.status', 1)->select('maintenance_shops.id', 'maintenance_shops.name', "resource_region.region_name")->get();
                $citys[] = array('id' => $_pas->city_id, 'item' => $ms);
            }
            foreach ($citys as $key => $city) {
                $cc = CommonCity::find($city['id']);
                $citys[$key]['name'] = $cc->name;
                foreach ($city['item'] as $item) {
                    if (in_array($item->id, $shop_ids)) {
                        $item->status = 1;
                    } else {
                        $item->status = 0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("shop_info" => $citys));
        } while (false);
        Log::info("info", array("system" => "scs", "event" => "shop_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 14:51:29
     * @Description: 配置优惠券门店
     */
    public function save_shops()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'coupon_base_id' => 'required',
                'shop_ids' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $shop_ids = json_decode(Input::get('shop_ids'), 1);
            // ProductActivityShop::where('product_activity_id',Input::get('product_activity_id'))->delete();
            CouponShop::where('coupon_base_id', Input::get('coupon_base_id'))->where('status', 1)->update(array('status' => 0));
            foreach ($shop_ids as $shop_id) {
                $pas = new CouponShop();
                $pas->coupon_base_id = Input::get('coupon_base_id');
                $pas->shop_id = $shop_id;
                $pas->created_by = $mkt_user->id;
                $pas->save();
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("coupon_base_id" => Input::get('coupon_base_id')));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "save_shops", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }



    /**
     *
     *
     *优惠活动的配置
     */


    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 15:43:56
     * @Description: 优惠活动城市配置
     */
    public function ac_city_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'activity_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $pas = ActivityCity::where("activity_id", Input::get('activity_id'))->where("status", 1)->get();
            $citys = array();
            foreach ($pas as $_pas) {
                $citys[] = $_pas->city_id;
            }

            $all_cit = DB::select("select rct.id,rct.name,rpt.id rid ,rpt.`name` p_name from resource_city_type rct LEFT JOIN resource_city rc on rc.id=rct.id
                    LEFT JOIN resource_province_type rpt on rpt.id=rc.province_id where rct.`status`=1");
            foreach ($all_cit as $_r) {
                if (isset($resource_arr[$_r->rid])) {
                    $temparr = $resource_arr[$_r->rid];
                    $temparr["item"][] = $_r;
                    $resource_arr[$_r->rid] = $temparr;
                } else {
                    $resource_arr[$_r->rid] = array(
                        'r_id' => $_r->rid,
                        'name' => $_r->p_name,
                        'item' => array($_r),
                    );
                }
            }
            $resource_arr = array_values($resource_arr);
            foreach ($resource_arr as $ra) {
                foreach ($ra['item'] as $item) {
                    if (in_array($item->id, $citys)) {
                        $item->status = 1;
                    } else {
                        $item->status = 0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('city_list' => $resource_arr));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "ac_city_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 15:55:45
     * @Description: 优惠活动的城市配置
     */
    public function ac_save_citys()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'activity_id' => 'required',
                'city_ids' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $city_ids = json_decode(Input::get('city_ids'));
            ActivityCity::where("activity_id", Input::get('activity_id'))->where("status", 1)->update(array('status' => 0));
            foreach ($city_ids as $_c) {
                $pas = new ActivityCity();
                $pas->activity_id = Input::get('activity_id');
                $pas->city_id = $_c;
                $pas->created_by = $mkt_user->id;
                $pas->save();
            }
            ActivityShop::where('activity_id', Input::get('activity_id'))->delete();
            ScNoticeShop::where('activity_base_id', Input::get('activity_id'))->delete();
            /**
             * 修改城市适配的时候，不修改当前城市下所有门店  20170925 赵洋
             */
//            $ms=MaintenanceShops::whereIn('city_id',$city_ids)->where('status',1)->get();
//            ActivityShop::where('activity_id',Input::get('activity_id'))->where('status',1)->update(array('status'=>0));
//            foreach($ms as $_ms){
//                $pas=new ActivityShop();
//                $pas->activity_id = Input::get('activity_id');
//                $pas->shop_id = $_ms->id;
//                $pas->created_by = $mkt_user->id;
//                $pas->save();
//            }

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("activity_id" => Input::get('activity_id')));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "ac_save_citys", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 16:12:12
     * @Description: 优惠活动的门店信息
     */
    public function ac_shop_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'activity_id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            $pas = ActivityCity::where("activity_id", Input::get('activity_id'))->where("status", 1)->get();
            $shop_ids = ActivityShop::where('activity_id', Input::get('activity_id'))->where('status', 1)->select("shop_id")->get()->toArray();
            $shop_ids = array_column($shop_ids, 'shop_id');
            $citys = array();
            foreach ($pas as $_pas) {
                // $ms=MaintenanceShops::where('city_id',$_pas->city_id)->where('status',1)->select('id','name')->get();
                $ms = MaintenanceShops::leftJoin("resource_region", "resource_region.id", "=", "maintenance_shops.region_id")->where('maintenance_shops.city_id', $_pas->city_id)->where('maintenance_shops.status', 1)->select('maintenance_shops.id', 'maintenance_shops.name', "resource_region.region_name")->get();
                $citys[] = array('id' => $_pas->city_id, 'item' => $ms);
            }
            foreach ($citys as $key => $city) {
                $cc = CommonCity::find($city['id']);
                $citys[$key]['name'] = $cc->name;
                foreach ($city['item'] as $item) {
                    if (in_array($item->id, $shop_ids)) {
                        $item->status = 1;
                    } else {
                        $item->status = 0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("shop_info" => $citys));
        } while (false);
        Log::info("info", array("system" => "scs", "event" => "shop_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-13 16:24:45
     * @Description: 配置优惠活动门店信息
     */
    public function ac_save_shops()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'activity_id' => 'required',
                'shop_ids' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {
            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }
            $shop_ids = json_decode(Input::get('shop_ids'), 1);
            // ProductActivityShop::where('product_activity_id',Input::get('product_activity_id'))->delete();
            ActivityShop::where('activity_id', Input::get('activity_id'))->where('status', 1)->update(array('status' => 0));
            foreach ($shop_ids as $shop_id) {
                $pas = new ActivityShop();
                $pas->activity_id = Input::get('activity_id');
                $pas->shop_id = $shop_id;
                $pas->created_by = $mkt_user->id;
                $pas->save();
            }

            //站内信优惠活动门店适配
            $shop = ScNoticeShop::ActivityShop(Input::get('activity_id'));
            $notice_id = ScNotice::Notice(Input::get('activity_id'), 3);
            if (is_null($notice_id)) {
                $response = Lang::get("mkt_error.mkt_notice_activity_exit_error_400001");
                break;
            }
            $notice = ScNotice::SaveShop(Input::get('activity_id'), 3, $shop_ids, $mkt_user->id, $notice_id['id']);

            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("activity_id" => Input::get('activity_id')));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "ac_save_shops", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-11-15 12:20:27
     * @Description: 优惠券增加生成数量
     * @Url: http://www.activity.com/v1/mkt/coupon/coupon_increment?token=0f6ef678e65c75bc35d202e6f123c6b3&id=206&num=1
     */
    public function coupon_increment()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => "required",
                'num' => "required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            //数据校验
            if(Input::get('num') > 5000 || Input::get('num') <= 0   ){
                $response = Lang::get("mkt_error.coupon_count_exit_error_510004");
                break;
            }
            $coupon_base = CouponBaseInfo::where('id', Input::get('id'))->where('num_type',0)->first();
            if (empty($coupon_base)) {
                $response = Lang::get("mkt_error.coupon_not_exit_error_510001");
                break;
            }
            $count = CouponIncrement::where('coupon_base_info_id',Input::get('id'))->where('status',1)->sum('count');
            $coupon_count = Coupons::where('coupon_base_info_id',Input::get('id'))->count();
            if($count != $coupon_count){
                $response = Lang::get("mkt_error.coupon_count_not_equal_error_510005");
                break;
            }
            $coupon_ids = CouponIncrement::where('coupon_base_info_id', Input::get('id'))->where('status',1)->first();
            if(!is_null($coupon_ids)){
                $type = 2;
            }else{
                $type = 1;
            }
            try {
                $coupon = new CouponIncrement();
                $coupon->coupon_base_info_id = Input::get('id');
                $coupon->count = Input::get('num',0);
                $coupon->type = $type;
                $coupon->created_at = Common::currentTimeString();
                $coupon->updated_at = Common::currentTimeString();
                $coupon->created_by = $mkt_user->id;
                $coupon->num_type = $coupon_base->num_type;
                $coupon->status = 1;
                if($coupon->save()){
                    $input = array(
                        'coupon_base_info_id' => Input::get('id'),
                        'status' => 1,
                        'received_user_id' => 0,
                        'used_user_id' => 0,
                        'created_at' => date('Y-m-d H:i:s', time()),
                        'updated_at' => date('Y-m-d H:i:s', time()),
                    );

                    $num = intval(Input::get('num'));
                    $limit = 5000;
                    $bag = array();
                    for ($i = 0, $j = 0; $i < $num; $i++) {
                        //生成统一的优惠码
                        if (Input::get('code_type',1) == 1) { //1 代表 随机码
                            $bonus_arr = Helper::getStr(Input::get('id'), $mkt_user->id);
                            if ((int)Input::get('type',1) == 1) {
                                $bonus_sn = 'jm' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                            }
                            if ((int)Input::get('type',1) == 2) {
                                $bonus_sn = 'fw' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                            }
                            if ((int)Input::get('type',1) == 3) {
                                $bonus_sn = 'sw' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                            }
                            if ((int)Input::get('type',1) == 4) {
                                $bonus_sn = 'fj' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                            }
                            if ((int)Input::get('type',1) == 5) {
                                $bonus_sn = 'fd' . date("m", time()) . date("d", time()) . $bonus_arr['str_num'];
                            }
                        } else {
                            $bonus_sn = Input::get('code');
                        }
                        $input['code'] = $bonus_sn;

                        $count = count($bag);
                        if ($count === $limit OR $count === ($num - 1)) {
                            if ($num - 1 != 0) {
                                DB::table('coupons')->insert($bag);
                            }
                            $bag = array();
                        }
                        $bag[] = $input;
                        $j++;
                    }
                    if (count($bag) > 0) {
                        DB::table('coupons')->insert($bag);
                        $bag = array();
                    }
                }

                $response = array('code' => 0, 'msg' => 'ok');
            } catch (Exception $e) {
                Log::error("error", array("system" => "mkt", "event" => "coupon_increment", 'input' => Input::all(), "exception" => $e));
                $response = Lang::get("mkt_error.coupon_increment__not_exit_error_510003");
                break;
            }
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_increment", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-11-15 12:20:27
     * @Description: 优惠券增加生成数量明细
     * @Url: http://www.activity.com/v1/mkt/coupon/coupon_increment_show?token=0f6ef678e65c75bc35d202e6f123c6b3&id=206&page=1&page_size=1
     */
    public function coupon_increment_show()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => "required",
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            //获取参数
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            //数据校验
            $coupon_base = CouponBaseInfo::where('id', Input::get('id'))->where('num_type',0)->first();
            if (empty($coupon_base)) {
                $response = Lang::get("mkt_error.coupon_not_exit_error_510001");
                break;
            }

            //获取数据
            $coupon_base = CouponIncrement::join('mkt_user','coupon_increment.created_by','=','mkt_user.id')->where('coupon_base_info_id',Input::get('id'))->where('coupon_increment.status',1)->select('coupon_increment.count','coupon_increment.created_at','mkt_user.real_name','mkt_user.user_name');
            $count=$coupon_base->count();
            $coupon_base=$coupon_base->skip($page_size*($page-1))->take($page_size)->get();
            //组织返回
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"coupon_base"=>$coupon_base));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_increment_show", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-11-15 12:20:27
     * @Description: 优惠券耗材列表
     * @Url: http://www.activity.com/v1/mkt/coupon/coupon_item_list?token=0f6ef678e65c75bc35d202e6f123c6b3&page=1&page_size=10&model=%E9%A9%AC%E8%87%AA%E8%BE%BE&name=%E5%8D%9A%E4%B8%96%EF%BC%88BOSCH%EF%BC%89%E7%B2%BE%E8%A3%85&brand_name=%E5%8D%9A%E4%B8%96%EF%BC%88BOSCH%EF%BC%89%E7%B2%BE%E8%A3%85
     */
    public function coupon_item_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result' => array());
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            //获取参数
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            //获取数据
            $si=SupplyItem::leftjoin('anhui_data.supply_unit as a','a.id','=','supply_item.unit_id')
                ->leftjoin('anhui_data.supply_unit as b','b.id','=','supply_item.sale_unit_id')
                ->where('supply_item.status',1)
                ->where('supply_item.type',0)
                ->orderby("supply_item.id","asc")
                ->select('supply_item.id','supply_item.anhui_code','supply_item.code','supply_item.name','supply_item.unit_id','supply_item.sale_unit_id','supply_item.volume_size','a.name as unit_name','b.name as sale_unit_name','supply_item.retrieval_code');
            if(Input::get("name")){
                $si->where("supply_item.retrieval_code","LIKE","%".Input::get("name")."%");
            }
            if(Input::get('brand_name')){
                $si->where("supply_item.retrieval_code","LIKE","%".Input::get("brand_name")."%");
            }
            if(Input::get('model')){
                $si->where("supply_item.retrieval_code","LIKE","%".Input::get("model")."%");
            }

            $count=$si->count();
            $si=$si->skip($page_size*($page-1))->take($page_size)->get();

            //组织返回
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"item_list"=>$si, 'type' => 'item'));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_item_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-11-15 17:46:27
     * @Description: 优惠券活动包列表
     * @Url: http://www.activity.com/v1/mkt/coupon/coupon_activity_list?token=0f6ef678e65c75bc35d202e6f123c6b3
     */
    public function coupon_activity_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            //获取参数
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            //获取数据
            $si=ProductActivity::where('status',1)->select('id','name')->orderBy('id','asc');

            $count=$si->count();
            $si=$si->skip($page_size*($page-1))->take($page_size)->get();

            //组织返回
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"activity_list"=>$si, 'type' => 'activity'));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_activity_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      sqq
     * @DateTime:    2018-11-16 12:20:27
     * @Description: 优惠券耗材分类列表（三级分类，第三级）
     * @Url: http://www.activity.com/v1/mkt/coupon/coupon_item_class_list?token=ffc0bb4f273081ecc79c1fd0b046ac94&name=%E6%89%8B%E5%8A%A8&page=1&page_size=2
     */
    public function coupon_item_class_list()
    {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok','result' => array());
        do {

            if ($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"] = $validator->messages()->all();
                break;
            }
            $mkt_user = $this->verificationMKTUserToken(Input::get("token"), $response);
            if (is_null($mkt_user)) {
                break;
            }

            //获取参数
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            //获取数据
            $si=SupplyClassification::where('status',1)
                ->where('level',3)
                ->orderby("id","asc")
                ->select('id','name');
            if(Input::get("name")){
                $si->where("name","LIKE","%".Input::get("name")."%");
            }

            $count=$si->count();
            $si=$si->skip($page_size*($page-1))->take($page_size)->get();

            //组织返回
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"item_class_list"=>$si, 'type' => 'item_class'));
        } while (false);
        Log::info("info", array("system" => "mkt", "event" => "coupon_item_class_list", 'input' => Input::all(), "output" => $response));
        return json_encode($response);
    }

}
